package com.hsmw.api.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Sets;
import com.hsmw.api.config.jwt.CurrentHsmwUserUtils;
import com.hsmw.api.controller.pub.TencentPushUtils;
import com.hsmw.api.mapper.HsmwConcretePlantInfoMapper;
import com.hsmw.api.mapper.HsmwDriverUserMapper;
import com.hsmw.api.mapper.HsmwHtnUserMapper;
import com.hsmw.api.vo.DriverAddressInfo;
import com.hsmw.api.vo.MyTotalInfoVO;
import com.hsmw.api.vo.PumpSetupInfoDTO;
import com.hsmw.api.vo.RetailerOrForemanInfoVO;
import com.hsmw.common.base.BasePage;
import com.hsmw.common.base.BaseService;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.*;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class HsmwHtnUserService extends BaseService<HsmwHtnUserMapper, HsmwHtnUser> {


    @Autowired
    private HsmwHtnUserMapper hsmwHtnUserMapper;


    @Autowired
    private CurrentHsmwUserUtils currentHsmwUserUtils;

    @Autowired
    private HsmwVehicleService hsmwVehicleService;
    @Autowired
    private HsmwInviteRecordService hsmwInviteRecordService;

    @Autowired
    private HsmwLeasingCompanyService hsmwLeasingCompanyService;

    @Autowired
    private HsmwConcretePlantInfoMapper hsmwConcretePlantInfoMapper;


    public HsmwHtnUser findByUsername(String username) {
        QueryWrapper<HsmwHtnUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(HsmwHtnUser::getUsername, username);
        return hsmwHtnUserMapper.selectOne(queryWrapper);
    }

    public IPage<HsmwHtnUser> getHsmwUserPage(IPage page, HsmwHtnUser hsmwUser) {
        LambdaQueryWrapper<HsmwHtnUser> queryWrapper = new LambdaQueryWrapper<>();
        if (!StrUtil.isBlank(hsmwUser.getName())) {
            queryWrapper.like(HsmwUser::getName, hsmwUser.getName());
        }
        if (!StrUtil.isBlank(hsmwUser.getUsername())) {
            queryWrapper.eq(HsmwUser::getUsername, hsmwUser.getUsername());
        }
        if (!StrUtil.isBlank(hsmwUser.getType())) {
            queryWrapper.eq(HsmwUser::getType, hsmwUser.getType());
        }
        if (!StrUtil.isBlank(hsmwUser.getItemId())) {
            queryWrapper.eq(HsmwUser::getItemId, hsmwUser.getItemId());
        }
        if (!StrUtil.isBlank(hsmwUser.getConstructionUnitId())) {
            String constructionUnitId = hsmwUser.getConstructionUnitId();
//			List<HsmwItem> hsmwItemList = hsmwItemService.list(Wrappers.lambdaQuery(HsmwItem.class).eq(HsmwItem::getConstructionUnitId, constructionUnitId));
//			queryWrapper.in(HsmwUser::getItemId, hsmwItemList.stream().map(HsmwItem::getId).collect(Collectors.toList()));
            queryWrapper.eq(HsmwUser::getConstructionUnitId, constructionUnitId);
        }
        IPage ipage = this.baseMapper.selectPage(page, queryWrapper.orderByDesc(HsmwHtnUser::getCreateTime));
        return ipage;
    }

    public List<HsmwHtnUser> getchooseForceManSelect(String itemId, String constructionUnitId) {
        HashSet<HsmwHtnUser> resultSet = Sets.newHashSet();
        List<HsmwHtnUser> hsmwUserList = hsmwHtnUserMapper.selectList(Wrappers.lambdaQuery(HsmwHtnUser.class)
                .eq(HsmwHtnUser::getType, CommonConstants.UserRole.FOREMAN.name())
                .eq(HsmwHtnUser::getConstructionUnitId, constructionUnitId));
        if (!StrUtil.isEmpty(itemId)) {
            List<HsmwHtnUser> itemUsers = hsmwHtnUserMapper.selectList(Wrappers.lambdaQuery(HsmwHtnUser.class)
                    .eq(HsmwHtnUser::getItemId, itemId));
            hsmwUserList.addAll(itemUsers);
        }
        return hsmwUserList.stream().distinct().collect(Collectors.toList());
    }


    public IPage<HsmwHtnUser> getPassRetailAuditPageInfo(IPage page, HsmwHtnUser hsmwUser) {
        LambdaQueryWrapper<HsmwHtnUser> queryWrapper = new LambdaQueryWrapper<>();
        //根据姓名或者手机号查询
        if (!StrUtil.isBlank(hsmwUser.getQueryParam())) {
            queryWrapper.like(HsmwUser::getName, hsmwUser.getQueryParam()).or().like(HsmwUser::getUsername,hsmwUser.getQueryParam());
        }
        LocalDateTime createTime = hsmwUser.getCreateTime();
        if (null!=(hsmwUser.getCreateTime())) {
            LocalDateTime tommorrow = hsmwUser.getCreateTime().plusDays(1);
            queryWrapper.ge(HsmwUser::getCreateTime, hsmwUser.getCreateTime());
            queryWrapper.lt(HsmwUser::getCreateTime, tommorrow);
        }
        queryWrapper.eq(HsmwUser::getForemanType,"0");
        queryWrapper.eq(HsmwUser::getAuditStatus, CommonConstants.YES);

        IPage<HsmwHtnUser> ipage = hsmwHtnUserMapper.selectPage(page, queryWrapper.orderByDesc(HsmwHtnUser::getCreateTime));
        return ipage;

    }


    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    public HsmwHtnUser getHsmwUserById(String id) {
        LambdaQueryWrapper<HsmwHtnUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HsmwUser::getId, id);
        return hsmwHtnUserMapper.selectOne(queryWrapper);
    }



    //散户审核通过
    public DataResponse passHsmwRetail(String key, String remark, String ownCompanyName) {
        HsmwHtnUser retail = hsmwHtnUserMapper.selectById(key);
        if(null== retail){
            return  DataResponse.failure(CommonConstants.ResponseStatus.VALIDATE_FAILED.getCode(),"当前用户不存在，请检查后重新输入！");
        }
        retail.setType(CommonConstants.UserRole.FOREMAN.name());
        //retai 设置Item相关信息。
        retail.setUpdateTime(LocalDateTime.now());
        retail.setRemark(remark);
        retail.setAuditStatus(AuditStatusEnum.RECEIVED.getValue());
        retail.setOwnCompanyName(ownCompanyName);
        retail.setItemId(CommonConstants.SANHU_ITEM);

        //给工长推送信息 搅拌站拒绝接单的信息
        String msg = "您的审核已通过，快去下单吧!";
        TencentPushUtils.pushForeManMsg(msg,retail.getUsername(),"has_new_message");
        TencentPushUtils.selfrunMsg(msg,retail.getUsername(),"has_new_message");
        hsmwHtnUserMapper.updateById(retail);
        return  new DataResponse();
    }

    //散户审核拒绝
    public void refuseHsmwRetail(String id, String remark) {
        HsmwHtnUser retail = hsmwHtnUserMapper.selectById(id);
        retail.setAuditStatus(AuditStatusEnum.FAILED.getValue());
        retail.setRemark(remark);
        hsmwHtnUserMapper.updateById(retail);
    }


    public IPage<HsmwHtnUser> getRetailAuditPageInfo(IPage page, HsmwHtnUser hsmwUser) {
        LambdaQueryWrapper<HsmwHtnUser> queryWrapper = new LambdaQueryWrapper<>();
        //根据姓名或者手机号查询
        if (!StrUtil.isBlank(hsmwUser.getQueryParam())) {
            queryWrapper.like(HsmwHtnUser::getName, hsmwUser.getQueryParam()).or().like(HsmwHtnUser::getUsername,hsmwUser.getQueryParam());
        }
        LocalDateTime createTime = hsmwUser.getCreateTime();
        if (null!=(hsmwUser.getCreateTime())) {
            LocalDateTime tommorrow = hsmwUser.getCreateTime().plusDays(1);
            queryWrapper.ge(HsmwHtnUser::getCreateTime, hsmwUser.getCreateTime());
            queryWrapper.lt(HsmwHtnUser::getCreateTime, tommorrow);

        }
        if (com.htn.common.core.utils.StringUtils.isNotBlank(hsmwUser.getAuditStatus()) ) {
            queryWrapper.eq(HsmwHtnUser::getForemanType,"0");
            queryWrapper.eq(HsmwHtnUser::getAuditStatus, hsmwUser.getAuditStatus());
        }
        queryWrapper.orderByDesc(HsmwHtnUser::getCreateTime);
        IPage<HsmwHtnUser> ipage = hsmwHtnUserMapper.selectPage(page, queryWrapper.orderByDesc(HsmwHtnUser::getCreateTime));
        return ipage;

    }



    public IPage<RetailerOrForemanInfoVO> getForemanList(BasePage page) {
        HashMap param =new HashMap();
        if(com.htn.common.core.utils.StringUtils.isNotBlank(page.getQueryParam())){
            param.put("queryParam",page.getQueryParam());
        }
        HashMap result = new HashMap();
        List<RetailerOrForemanInfoVO> allUserList = hsmwHtnUserMapper.getForemanList(param);
        param.put("pageStart",(page.getPageNo()-1) * page.getPageSize());
        param.put("pageSize",page.getPageSize());
        List<RetailerOrForemanInfoVO> userList =  hsmwHtnUserMapper.getForemanList(param);
        IPage<RetailerOrForemanInfoVO> 	 userListPage =new Page<>();
        userListPage.setTotal(allUserList.size());
        userListPage.setCurrent(page.getPageNo());
        userListPage.setRecords(userList);
        userListPage.setSize(page.getPageSize());
        long total = allUserList.size();
        long pages = 0;
        pages = total/page.getPageSize();
        if(total% page.getPageSize() !=0){
            pages = pages+1;
        }
        userListPage.setPages(pages);
        return userListPage;
    }

    public IPage<RetailerOrForemanInfoVO> getRetailerList(BasePage page) {
        HashMap param =new HashMap();
        if(com.htn.common.core.utils.StringUtils.isNotBlank(page.getQueryParam())){
            param.put("queryParam",page.getQueryParam());
        }
        HashMap result = new HashMap();
        List<RetailerOrForemanInfoVO> allUserList = hsmwHtnUserMapper.getRetailerList(param);
        param.put("pageStart",(page.getPageNo()-1) * page.getPageSize());
        param.put("pageSize",page.getPageSize());
        List<RetailerOrForemanInfoVO> userList =  hsmwHtnUserMapper.getRetailerList(param);
        IPage<RetailerOrForemanInfoVO> 	 userListPage =new Page<>();
        userListPage.setTotal(allUserList.size());
        userListPage.setCurrent(page.getPageNo());
        userListPage.setRecords(userList);
        userListPage.setSize(page.getPageSize());
        long total = allUserList.size();
        long pages = 0;
        pages = total/page.getPageSize();
        if(total% page.getPageSize() !=0){
            pages = pages+1;
        }
        userListPage.setPages(pages);
        return userListPage;
    }

    public void removeItemInfoById(HashMap param) {
        hsmwHtnUserMapper.removeItemInfoById(param);
    }

    public void removeItemInfoByItemId(HashMap param) {
        hsmwHtnUserMapper.removeItemInfoByItemId(param);
    }


    public void removeStuff(HashMap param) {
        hsmwHtnUserMapper.removeStuff(param);
    }

    public MyTotalInfoVO getMytotalInfo(HashMap param) {
        return  hsmwHtnUserMapper.getMytotalInfo(param);
    }
    public MyTotalInfoVO getForemantotalInfo(HashMap param) {
        return  hsmwHtnUserMapper.getForemantotalInfo(param);
    }

    public DataResponse pumpSetupInfo() {
        PumpSetupInfoDTO pumpSetupInfoDTO = new PumpSetupInfoDTO();
        HsmwHtnUser currentHtnUser = currentHsmwUserUtils.getCurrentHtnUserInfo() ;
        //如果是公司用户 那么查询自营公司的数量
        if (HtnUserTypeEnum.COMPANY.getValue().equals(currentHtnUser.getType())){
            List<HsmwVehicle> hsmwVehicles = hsmwVehicleService.list(new LambdaQueryWrapper<HsmwVehicle>()
                    .eq(HsmwVehicle::getLeasingCompanyId,currentHtnUser.getOwnCompanyId()));
            List<HsmwInviteRecord> records =hsmwInviteRecordService.list(new LambdaQueryWrapper<HsmwInviteRecord>()
                    .eq(HsmwInviteRecord::getInviteCompanyId,currentHtnUser.getOwnCompanyId())
                    .eq(HsmwInviteRecord::getInviteType, InviteTypeEnum.COMPANY_INVITE_CORPERATE.getValue()));
            pumpSetupInfoDTO.setVehicleCount(CollectionUtil.isNotEmpty(hsmwVehicles) ?hsmwVehicles.size(): 0 );
            pumpSetupInfoDTO.setCorperateInviteRecords(records);
            HsmwLeasingCompany company = hsmwLeasingCompanyService.getById(currentHtnUser.getOwnCompanyId());
            pumpSetupInfoDTO.setEnableFlag(company.isEnableFlag());
            pumpSetupInfoDTO.setOpenFlag(company.isOpenFlag());
        }
        //如果是 搅拌站用户 那么查询自营优先的 邀请信息 和 合作公司的邀请信息
        if (HtnUserTypeEnum.CONCRETE.getValue().equals(currentHtnUser.getType())){
            HsmwInviteRecord record =hsmwInviteRecordService.getOne(new LambdaQueryWrapper<HsmwInviteRecord>()
                    .eq(HsmwInviteRecord::getInviteCompanyId,currentHtnUser.getOwnCompanyId())
                    .eq(HsmwInviteRecord::getInviteType,InviteTypeEnum.CONCRETE_INVITE_SELFRUN.getValue()));
            if(StringUtils.isNotNull(record)){
                List<HsmwVehicle> hsmwVehicles = hsmwVehicleService.list(new LambdaQueryWrapper<HsmwVehicle>()
                        .eq(HsmwVehicle::getLeasingCompanyId,record.getCompanyId()));
                record.setVehicleCount(CollectionUtil.isNotEmpty(hsmwVehicles) ?hsmwVehicles.size(): 0 );
                pumpSetupInfoDTO.setSelfrunRecord(record);
            }else {
                pumpSetupInfoDTO.setVehicleCount(0);
            }

            List<HsmwInviteRecord> records =hsmwInviteRecordService.list(new LambdaQueryWrapper<HsmwInviteRecord>()
                    .eq(HsmwInviteRecord::getInviteCompanyId,currentHtnUser.getOwnCompanyId())
                    .eq(HsmwInviteRecord::getInviteType, InviteTypeEnum.CONCRETE_INVITE_CORPERATE.getValue()));
            pumpSetupInfoDTO.setCorperateInviteRecords(records);
            HsmwConcretePlantInfo  plantInfo = hsmwConcretePlantInfoMapper.selectById(currentHtnUser.getOwnCompanyId());
            pumpSetupInfoDTO.setEnableFlag(plantInfo.isEnableFlag());
            pumpSetupInfoDTO.setOpenFlag(plantInfo.isOpenFlag());

        }
        return  new DataResponse(pumpSetupInfoDTO);
    }

    public DataResponse getAvaliableCompany(String type) {
        //2 . 租赁公司查询可用合作公司 3.搅拌站查询自营公司 4. 搅拌站查询合作公司
        HsmwHtnUser currentHtnUser = currentHsmwUserUtils.getCurrentHtnUserInfo() ;
        HashMap param = new HashMap();
        if (InviteTypeEnum.COMPANY_INVITE_CORPERATE.getValue().equals(type)){
            param.put("inviteType",type);
        }
        if (InviteTypeEnum.CONCRETE_INVITE_SELFRUN.getValue().equals(type)){
            param.put("inviteType",InviteTypeEnum.CONCRETE_INVITE_CORPERATE.getValue());
        }
        if (InviteTypeEnum.CONCRETE_INVITE_CORPERATE.getValue().equals(type)){
            param.put("inviteType",InviteTypeEnum.CONCRETE_INVITE_SELFRUN.getValue());
        }
        if(HtnUserTypeEnum.COMPANY.getValue().equals(currentHtnUser.getType())){
            param.put("companyId",currentHtnUser.getOwnCompanyId());
        }
        param.put("userId",currentHtnUser.getId());
        List<HsmwLeasingCompany>  companies = hsmwLeasingCompanyService.getAvaliableSelfCompany(param);
        if(CollectionUtil.isNotEmpty(companies)){
            for(HsmwLeasingCompany  company :companies){
                List<HsmwHtnUser> users = hsmwHtnUserMapper.selectList(new LambdaQueryWrapper<HsmwHtnUser>()
                        .eq(HsmwHtnUser::getOwnCompanyId,company.getId())
                        .eq(HsmwHtnUser::getRoleType, HtnUserRoleEnum.LEADING.getValue()));
                HsmwHtnUser user = users.get(0);
                company.setUserId(user.getId());
                company.setLinkMan(user.getName());
            }
        }
        return  new DataResponse(companies);

    }

    public void unregisterUser(String id) {
        hsmwHtnUserMapper.unregisterUser(id);
    }

    public List<DriverAddressInfo> queryAddressList(HashMap param) {

        return hsmwHtnUserMapper.queryAddressList(param);
    }
}
